<?php
namespace Admin\Controller;
use Think\Controller;
class BaseController extends Controller {
    protected function _initialize() {
        $this->checklogin();
        $this->_header();
        $this->_slide();
	}
    public function index(){
        $this->display();
    }
    public function _header(){
        $m_node=M("node");
        $prefix=columnKeyPrefix($m_node);
        $map=mapStatus($prefix);
        $map['no_pid']=0;
        $nav=$m_node
            ->where($map)
            ->order($prefix.'_createtime asc,'.$prefix.'_order desc')
            ->select();
        foreach ($nav as &$value) {
            $find=$m_node
                 ->where(array('no_pid'=>$value['no_id']))
                 ->find();
            if($value['no_name']=='Index'){
               $value['controller']='Index';
            }else{
               $value['controller']=$find['no_name']; 
            }
            
        }
        //$nav[0]['controller']='Index';
        $this->assign("head_nav",$nav);
    }
    public function _slide(){
        $model=D('node');
        $Controller=CONTROLLER_NAME;
        $prefix=columnKeyPrefix($model);
        $mapn=mapStatus($prefix);
        $mapn['no_name']=$Controller;
        
        $con=$model
           ->where($mapn)
           ->field(array('no_id','no_pid'))
           ->find();
        $pid=$con['no_pid'];
        $field=array('no_pid','no_id','no_name','no_show_name');

        $mapy=mapStatus($prefix);
        $mapy['no_pid']=$pid;
        $slide=$model
              ->where($mapy)
              ->field($field)
              ->select();
        // 
        $relationModel=array('Node');
        $relationName=array('son');
        $relationKey=array(array('no_id'=>'no_pid'));
        $relationField=array($field);
        $slide=D('Node')->relationModel($slide,$relationModel,$relationName,$relationKey,$relationField);
        $this->assign('slide_nav',$slide);
        //目前控制器的父节点名称
        $fathername=$model->where(array('no_id'=>$pid))->getField('no_name');
        $this->assign('father',$fathername);

    }
    /**
     * *
     * @return [type] [异步获取数据]
     */
    function ajaxlist(){
        $json=I('json');
        $where=$this->_checkmap();
        $field=ArrayToOne($json,'column');//拾取需要返回的字段
        $model=checkmodel(CONTROLLER_NAME);
        //获取字段前缀
        $prefix=columnKeyPrefix($model);
        $data=getList(checkmodel(),$field,$where,'',false,false,7);

        $tr='';
        foreach ($data['mainData'] as $value) {
            $td='';
            $i=0;
            foreach ($value as $key=> $val) {
              if($json[$i]['fun']){
                 $td.='<td>'.$json[$i]['fun']($val).'</td>';
              }else{
                 $td.='<td>'.$val.'</td>';
              } 
               $i++;  
            }
            $td=$td.'<td align="center"><a class="btn btn-success" href="'.U('edit',array('id'=>$value[$prefix.'_id'])).'">编辑</a>&nbsp;&nbsp;&nbsp;<a class="btn btn-danger xkdelete" href="'.U('dodelete',array('id'=>$value[$prefix.'_id'])).'">删除</a></td>';
            $tr.='<tr>'.$td.'</tr>';
        }
        $return=array(
            'tr'=>$tr,
            'page'=>$data['page']
        );
        if($data['total']>0){
            ajaxsuccess($return);
        }else{
            ajaxerror();
        }
        
    }

    function _checkmap(){
        $where= I('where');
        if (empty($where)) return '';
        foreach ($where as &$value) {
            $value=array('like','%'.$value.'%');
        } 
        return $where;
    }

    function edit($xk=true){
        if($xk){
            $model=checkmodel(CONTROLLER_NAME);
            $columnKey=columnKey($model);
            $map[$columnKey]=I('id');
            $list=getList($model,'',$map,'','',false);
            $this->assign('list',$list['mainData'][0]);
            $this->assign('columnKey',$columnKey);
        }
        $this->display('edit');
    }

    function add(){
        R('Admin/'.CONTROLLER_NAME.'/edit',array(false));
    }

    function doedit($action='edit'){
        $map=array($_POST['key']=>$_POST['keyvalue']);
        $model=checkmodel(CONTROLLER_NAME);
        $data=$model->create();
        //模型处过滤
        if(!$data){
           $msg=$model->getError();
           if($_POST['noajax']!==0){
                echo'<script>alert("'.$msg.'");</script>';die();
                  
            }
           $this->error($msg);
        }
        //图片文件上传检测
        if($_POST['uploadkey']){
             $isfile=$_FILES[$_POST['uploadkey']]['name'][0];
             //echo json_encode($_FILES);die();
             //die(json_encode($isfile[0]));
             //判断图片上传是否为空
             if($isfile!=""){
                 $info=$this->uploads();
                 if($info['status']!==1){
                      echo'<script>alert("'.$info["msg"].'");</script>';die();
                 }else{
                      
                      //相册上传
                      if($_POST['noajax']=='album'){
                            $sa=array();
                            $image = new \Think\Image();
                            
                            foreach ($info["msg"] as  $value) {
                               array_push($sa,'/Uploads/'.$value['savepath'].$value['savename']);
                               $image->open('./Uploads/'.$value['savepath'].$value['savename']);
                               $image->thumb(800,800,\Think\Image::IMAGE_THUMB_FIXED)->save('./Uploads/'.$value['savepath'].$value['savename']);
                               $image->thumb(350,350,\Think\Image::IMAGE_THUMB_FIXED)->save('./Uploads/'.$value['savepath'].'ss'.$value['savename']);
                            }
                            $string=implode(',',$sa);
                            if($action=='edit'){
                                $alrt=$model
                                     ->where($map)
                                     ->getField($_POST['uploadkey']);
                                $data[$_POST['uploadkey']]=$alrt.','.$string;
                            }else{
                                $data[$_POST['uploadkey']]=$string;
                            }
                      //图片上传
                      }elseif($_POST['noajax']=='image'){
                            $data[$_POST['uploadkey']]='/Uploads/'.$info["msg"][0]['savepath'].$info["msg"][0]['savename'];
                      }
                      
                 }
             }
             
        }

        if($action=='add'){
           $rt=add($data,$model);
        }else{
           $rt=edit($data,$map,$model); 
        }
        
        if($rt){
            if($_POST['noajax']!=0){
                $url=U(CONTROLLER_NAME.'/index');
                echo'<script>parent.window.dumpdirect("'.$url.'")</script>';die();
                
                  
            }
            $this->success('编辑成功');
            
            
        }else{
            if($_POST['noajax']!==0){
                echo'<script>alert("编辑失败");</script>';die();
            }
            $this->error('编辑失败');
            
            
        }

    }
    function doadd(){
        $this->doedit('add');
    }
    function dodelete(){
        $getid=I('get.id');
        $id=is_array($getid)?$getid:array($getid);
        $model=checkmodel();
        $key=columnKey($model);
        $map=array($key=>array('in',$id));
        //echo json_encode($map);die();
        $rt=dodelete($map,$model);
        if($rt){
            $this->success('删除成功！');
        }else{
            $this->error('失败');
        }
    }
    //是否登录
    function checklogin(){
        if(session('uid')){
        
        }else{
            $this->error('请登录',U('NoBase/login'));
        }
    }

    public function uploads(){
        $config = array(
            'maxSize'    =>    3145728,
            'rootPath'   =>    './Uploads/',
            'savePath'   =>    date('Y',time()).'/'.date('m',time()).'/',
            'saveName'   =>    array('uniqid',''),
            'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
            'autoSub'    =>    true,
            'subName'    =>    array('date','d'),
        );
        $upload = new \Think\Upload($config);// 实例化上传类
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $array=array('status'=>0,'msg'=>$upload->getError());
            return $array;
            //$this->error($upload->getError());
        }else{// 上传成功
            $array=array('status'=>1,'msg'=>$info);
            return $array;
        }
    }

    



}